# -*- coding: utf-8 -*-
import time

import dht
from machine import ADC, PWM, Pin, Timer

try:
    import ujson as json
except ImportError:
    import json

class Func():
    def __init__(self):
        self.switch_gpio = 16          # 开关引脚
        self.switch_Pin = None
        self.switch_state = 0          # 开关状态（默认低电平）      

        self.dht_gpio   = 13           # DHT温度湿度引脚
        self.dht_Pin    = None
        self.dht_tim    = Timer(-1)
        self.dht_state  = 0

        self.light_gpio = 'ADC'         # 光感引脚
        if type(self.light_gpio) is int:
            self.light_Pin  = Pin(self.light_gpio, Pin.IN)
        self.light_tim  = Timer(-1)
        self.light_state = 0

        self.button()

    def send(self, text=''):
        self.mqtt_send(text)

    # ===== 开关事件 Start =======
    def switch(self, gpio, state):
        if len(str(gpio))>0:
            if int(self.switch_gpio) != int(gpio):
                self.switch_gpio = int(gpio)
                self.switch_Pin = None
        
        if self.switch_Pin == None:
            self.switch_Pin = Pin(self.switch_gpio, Pin.OUT)

        if state==1:
            self.switch_Pin.off()
            self.switch_state = 1
        elif state==0:
            self.switch_Pin.on()
            self.switch_state = 0
        else:
            if int(self.switch_Pin.value()) == 1:
                self.switch_state = 0
            else:
                self.switch_state = 1

        self.send({'type':'switch','state': self.switch_state})
    # ===== 开关事件 End =========

    # === 温度湿度 Start ===
    def dht_recv(self, e):
        temp_val = 0
        humi_val = 0
        adc_val = 0
        try:
            d = dht.DHT11( Pin(self.dht_gpio) )
            d.measure()
            temp_val = d.temperature()
            humi_val = d.humidity()
            adc = ADC(0)
            adc_val = adc.read()
        except:pass

        data = {'temperature': str(temp_val), 'humidity': str(humi_val), 'adc': str(adc_val)}
        self.send({'type':'dht','state': data })

    # 温度湿度启停控制
    def dhtonoff(self, state, period=2000):
        if state == 1:
            self.dht_tim.init(period=period, mode=Timer.PERIODIC, callback=self.dht_recv)
            self.dht_state = 1
        elif state == 0:
            self.dht_tim.deinit()
            self.dht_state = 0
        else:
            self.send({'type':'dht','state': self.dht_state })

    # === 温度湿度 End ===

    def mqtt_send(self, Data=''):
        # 发送函数
        # 被外部修改 重定义到外面
        pass

    # 回调处理
    def mqtt_receive(self, topic, rejson):
        print("回调收到消息", rejson )
        # try:
        if 'type' in dict(rejson).keys():
            state = ''
            if 'state' in dict(rejson).keys():
                state = rejson['state']

            gpio = ''
            if 'pin' in dict(rejson).keys():
                gpio = rejson['pin']

            if rejson['type'] == 'switch':
                self.switch(gpio, state)

            if rejson['type'] == 'dht':
                period = 2000
                self.dht_gpio = gpio
                if 'timer' in rejson and type(rejson['timer']) is int:
                    period = rejson['timer']
                self.dhtonoff(state, period)

            if rejson['type'] == 'MQTTCMD':
                print("MQTTCMD", rejson['MQTTCMD'])
                exec(rejson['MQTTCMD'])

        # except:
        #     print('JSON格式错误')
        #     pass

    # 按钮事件
    def button(self):
        def key_run(e):
            self.send({'type':'button','state': 1})

        button_pin = Pin(15, Pin.IN)
        button_pin.irq(trigger=Pin.IRQ_FALLING, handler=key_run)

